// store/Counter.ts
import { action, makeObservable, observable } from 'mobx'
import { getAllNoteList } from '../api/note'
import dayjs from 'dayjs'
import { v4 as uuidv4 } from 'uuid'

class Note {
  constructor() {
    // 参数1：target，把谁变成响应式（可观察）
    // 参数2：指定哪些属性或者方法变成可观察
    makeObservable(this, {
      allNoteList: observable,
      noteList: observable,
      bookmarkList: observable,
      trashList: observable,

      init: action,
      updateNoteList: action,
      getNote: action,
      saveNote: action, // 保存
      changeBookmark: action, // 收藏
      removeToTrash: action,// 移到回收站
      restoreNote: action, // 恢复
      delNote: action, // 清除
      clearTrash: action, // 清空回收站
      reset: action
    })
  }

  allNoteList = []
  noteList = []
  bookmarkList = []
  trashList = []

  async init() {
    try {
      const list = window.api.getStoreValue('notes') || []
      this.allNoteList = list || []
      this.updateNoteList()
    } catch (e) {
      console.log(e)
    }
  }

  updateNoteList() {
    // 跟新排序
    this.allNoteList.sort((a, b) => {
      console.log(dayjs(a.updateTime).diff(dayjs(b.updateTime)))
      return dayjs(b.updateTime).diff(dayjs(a.updateTime))
    })
    console.log('updateNoteList', this.allNoteList)
    this.noteList = this.allNoteList.filter(item => item.isDelete !== 1)
    this.bookmarkList = this.allNoteList.filter(item => item.isDelete !== 1 && item.isBookmark === 1)
    this.trashList = this.allNoteList.filter(item => item.isDelete === 1)
    try {
      window.api.setStoreValue('notes', JSON.parse(JSON.stringify(this.allNoteList)))
    } catch (e) {
      console.log(e)
    }
  }

  getNote(noteId) {
    if (!noteId) {
      return {}
    }
    try {
      if (this.allNoteList.length) {
        let noteItem = {}
        noteItem = this.allNoteList.find((item) => item.id === noteId)
        return noteItem
      } else {
        return {}
      }
    } catch (e) {
      return {}
    }
  }

  saveNote(noteItem) {
    return new Promise((resolve, reject) => {
      try {
        let noteId = ''
        if (noteItem.id) {
          noteId = noteItem.id
          const noteIndex = this.allNoteList.findIndex((item) => item.id === noteItem.id)
          if (noteIndex === -1) {
            return reject(new Error('非法ID'))
          }
          this.allNoteList[noteIndex] = {
            ...noteItem,
            updateTime: dayjs().format()
          }
        } else {
          noteId = uuidv4()
          this.allNoteList.push({
            ...noteItem,
            id: noteId,
            createTime: dayjs().format(),
            updateTime: dayjs().format()
          })
        }
        this.updateNoteList()
        resolve(noteId)
      } catch (e) {
        return reject(e)
      }
    })
  }

  // 修改收藏状态
  changeBookmark(noteId, status) {
    return new Promise((resolve, reject) => {
      try {
        if (!noteId || ![0, 1].includes(status)) {
          return reject(new Error('参数非法'))
        }

        const noteIndex = this.allNoteList.findIndex((item) => item.id === noteId)
        if (noteIndex === -1) {
          return reject(new Error('非法ID'))
        }
        this.allNoteList[noteIndex] = {
          ...this.allNoteList[noteIndex],
          isBookmark: status,
          // updateTime: dayjs().format()
        }
        this.updateNoteList()
        resolve()
      } catch (e) {
        return reject(e)
      }
    })
  }

  removeToTrash(noteId) {
    return new Promise((resolve, reject) => {
      try {
        if (!noteId) {
          return reject(new Error('参数非法'))
        }

        const noteIndex = this.allNoteList.findIndex((item) => item.id === noteId)
        if (noteIndex === -1) {
          return reject(new Error('非法ID'))
        }
        this.allNoteList[noteIndex] = {
          ...this.allNoteList[noteIndex],
          isDelete: 1,
          updateTime: dayjs().format()
        }
        this.updateNoteList()
        resolve()
      } catch (e) {
        return reject(e)
      }
    })
  }

  restoreNote(noteId) {
    return new Promise((resolve, reject) => {
      try {
        if (!noteId) {
          return reject(new Error('参数非法'))
        }

        const noteIndex = this.allNoteList.findIndex((item) => item.id === noteId)
        if (noteIndex === -1) {
          return reject(new Error('非法ID'))
        }
        this.allNoteList[noteIndex] = {
          ...this.allNoteList[noteIndex],
          isDelete: 0,
          updateTime: dayjs().format()
        }
        this.updateNoteList()
        resolve()
      } catch (e) {
        return reject(e)
      }
    })
  }

// 删除
  delNote(noteId) {
    return new Promise((resolve, reject) => {
      try {
        if (!noteId) {
          return reject(new Error('参数非法'))
        }

        const noteIndex = this.allNoteList.findIndex((item) => item.id === noteId)
        if (noteIndex === -1) {
          return reject(new Error('非法ID'))
        }
        this.allNoteList.splice(noteIndex, 1)
        this.updateNoteList()
        resolve()
      } catch (e) {
        return reject(e)
      }
    })
  }

// 清空回收站
  clearTrash() {
    return new Promise((resolve, reject) => {
      try {
        this.allNoteList = this.allNoteList.filter((item) => item.isDelete !== 1)

        this.updateNoteList()
        resolve()
      } catch (e) {
        return reject(e)
      }
    })
  }


  reset() {
    this.allNoteList = []
    this.noteList = []
    this.bookmarkList = []
    this.trashList = []
    try {
      window.api.setStoreValue('notes', [])
    } catch (e) {
      console.log(e)
    }
  }
}

const noteStore = new Note()
export default noteStore
